﻿
# DevScope BI PowerShell Samples
# 
# http://devscopebisamples.codeplex.com/
# http://www.devscope.net

write-host "---MailTodayOutliers---"

Import-Module .\DevScope.BI.Samples.PowerShell.psm1 -Force

. .\execconfig.ps1

$reportViewsSchema="mon"

Invoke-OLEDBCommand -connectionString $connStr `
	-sql "select Name from sys.views where SCHEMA_NAME(schema_id) = '$reportViewsSchema'" |%  {
	
	# for each view found
	$viewName = $reportViewsSchema+"."+$_.Name
	
	$data = Invoke-OLEDBCommand -connectionString $connStr -sql "select * from $viewName"

	$firstDateCol=	$data[0].Table.Columns | ? {$_.DataType -eq [datetime]} | select -index 1 | select $_.ColumnName

	write-host $firstDateCol

	$dmTable = Set-Outliers -dataTable $data[0].Table -connectionString $ssasconn

	write-host "Evaluating OutlierProbability threshold..."
	$x=$dmTable |  sort-object OutlierProbability -descending | select -index 5| select OutlierProbability 

	write-host "Highlighting..."
	$dmTable=$dmTable | ? {($_.$firstDateCol -ge [System.DateTime]::Now.Date )} | select *,@{name="SysRowCssClass";expression={if ($_.OutlierProbability -ge $x.OutlierProbability ){ "highlight" } else { "" }}} | sort-object $firstDateCol.ColumnName -descending


	$alertCount=($dmTable | ? {$_.SysRowCssClass -like "highlight"}).COunt
	write-host "Today outliers: $alertCount"

	# send mail only if alert column is present and its 1
	if ($alertCount -gt -1) 
		{
		$html = Out-Email -subject "Outliers in $viewName : $alertCount (today)" -inputObject $dmTable -to $mailto -from $mailfrom -smtpServer $mailsmtp
		}

}

write-host "Done!"


